package com.epam.lissina.separator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.epam.lissina.controller.Runner;
import com.epam.lissina.entity.IParagraph;
import com.epam.lissina.entity.Listing;
import com.epam.lissina.entity.Paragraph;
import com.epam.lissina.entity.Sentence;
import com.epam.lissina.entity.Title;
import com.epam.lissina.entity.Word;

public class TextSeparator {

	public static final String ENTER = "\r\n";
	public static final String EMPTY_LINE = "";
	public static final String BEGIN_PARAGRAPH_TAB = "\t";
	public static final String BEGIN_PARAGRAPH_SPACE = "    ";

	public static List<IParagraph> parseText(String text) {

		List<IParagraph> paragraphsList = new ArrayList<IParagraph>();

		String[] lines = text.split(ENTER);

		int index = 0;
		while (index < lines.length) {
			String paragraph = lines[index];
			if (paragraph.startsWith(Runner.rb.getString("RegCommentAll"))
					|| paragraph.startsWith(Runner.rb
							.getString("RegCommentLine"))) {
				int end = getCodeEnd(lines, index);

				String[] codeLines = Arrays.copyOfRange(lines, index, end);

				paragraphsList.add(new Listing(codeLines));
				index = end - 1;

			} else if (paragraph.startsWith(BEGIN_PARAGRAPH_TAB)
					|| paragraph.startsWith(BEGIN_PARAGRAPH_SPACE)) {
				Pattern end = Pattern.compile(Runner.rb
						.getString("RegParagraphEnd"));
				char last = paragraph.charAt(paragraph.length() - 1);
				if (end.matcher(String.valueOf(last)).matches()) {
					paragraphsList.add(new Paragraph(paragraph));
				} else {
					paragraphsList.add(new Title(paragraph));
				}
			}
			index++;
		}
		return paragraphsList;
	}

	private static int getCodeEnd(String[] lines, int startIndex) {
		int index = startIndex;
		while (index < lines.length - 1) {
			String line = lines[index++];
			if (line.isEmpty()) {
				return index;
			}
		}
		return lines.length - 1;
	}

	public static List<Sentence> parseParagraph(String text) {
		List<Sentence> sentencesList = new ArrayList<Sentence>();
		Pattern end = Pattern.compile(Runner.rb.getString("RegSentence"));

		Matcher endMatcher = end.matcher(text.trim());
		while (endMatcher.find()) {
			String sentence = endMatcher.group();
			sentencesList.add(new Sentence(sentence));
		}

		if (sentencesList.size() == 0) {
			sentencesList.add(new Sentence(text.trim()));
		}
		return sentencesList;
	}

	public static List<Word> parseSentence(String text) {

		List<Word> wordsList = new ArrayList<Word>();
		Pattern end = Pattern.compile(Runner.rb.getString("RegWord"));
		String[] words = end.split(text);

		int index = 0;
		while (index < words.length) {
			String word = words[index];
			wordsList.add(new Word(word));
			index++;
		}
		return wordsList;
	}
}